package com.lx.screenshot.ui;

import android.content.Context;
import android.content.Intent;
import android.media.projection.MediaProjectionManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;

import android.provider.Settings;
import android.util.Log;
import android.view.WindowManager;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;
import com.lx.screenshot.util.ScreenShotUtil;

public class ScreenRecordActivity extends AppCompatActivity {
    private static final int REQUEST_SCREEN_PERMISSION_CODE = 0x166;
    private static final int REQUEST_FLOAT_PERMISSION_CODE = 0x167;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().clearFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);

        Intent intent = getIntent();
        String from = intent.getStringExtra("from");
        if("float".equals(from)){
            goToPermissionSetting();
        }else {
            requestCapturePermission();
        }
    }

    /**
     * 跳转到本应用的悬浮窗设置
     */
    private void goToPermissionSetting() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            // 请求截屏权限 ACTION_MANAGE_OVERLAY_PERMISSION
            Intent intentAlertWindow = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS, Uri.parse("package:" + getPackageName()));
            startActivityForResult(intentAlertWindow, REQUEST_FLOAT_PERMISSION_CODE);
        }
    }

    //请求权限
    private void requestCapturePermission() {
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
            //5.0 之后才允许使用屏幕截图
            return;
        }
        MediaProjectionManager projectionManager = null;
//        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
        projectionManager = (MediaProjectionManager) getSystemService(Context.MEDIA_PROJECTION_SERVICE);
        startActivityForResult(projectionManager.createScreenCaptureIntent(), REQUEST_SCREEN_PERMISSION_CODE);
//            }
    }


    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        finish();
        ScreenShotUtil.onActivityResult(requestCode, resultCode, data, null, null);

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        Log.e("ScreenRecordActivity：", "onDestroy");
    }
}
